package top.chenfu.cloud.item.controller;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.chenfu.cloud.commons.Item;
import top.chenfu.cloud.commons.util.ResponseData;
import top.chenfu.cloud.item.service.ItemService;

import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;

/**
 * @Auther chenfu
 * @2019/12/5 20:07
 * @Desc
 */
@RestController
@RequestMapping(value = "item")
public class ItemController {

    //    暂时代替数据库
    private static HashMap<String, Item> items = Maps.newHashMap();

    @Autowired
    private ItemService itemService;

    @Value(value = "${spring.datasource.password:test}")
    private String testValue;

    @GetMapping(value = "/index", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData index() {
        return ResponseData.defaultSuccess(testValue);
    }

    @PostMapping(value = "add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData addItem(Item item) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        item.setId(uuid);
        items.put(uuid, item);
        return ResponseData.defaultSuccess(item);
    }

    @GetMapping(value = "all", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData getItems() {
        Object items = itemService.findItems();
        return ResponseData.defaultSuccess(items);
    }

    @GetMapping(value = "get/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData getItemById(@PathVariable String id) {
        if (StringUtils.isEmpty(id)) {
            return ResponseData.defaultFail();
        }
        Item item = items.get(id);
        if (Objects.isNull(item) || item.getStatus().equalsIgnoreCase("1")) {
            return ResponseData.defaultFail();
        }
        return ResponseData.defaultSuccess(item);
    }

    @DeleteMapping(value = "del/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData delItemById(@Validated @PathVariable String id, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseData.defaultFail();
        }
        Item item = items.get(id);
        if (Objects.isNull(item) || item.getStatus().equalsIgnoreCase("1")) {
            return ResponseData.defaultFail();
        }
        item.setStatus("1");
        return ResponseData.defaultSuccess();
    }

}
